<template>
  <div
    class="page-form-item"
    :class="{'cell-input': cellInput}"
    v-if="exits"
    v-show="show"
    :style="{display, width, height: heightCup,textAlign:'center',border:'none'}"
  >
      <div
        v-if="['text','password','textarea'].includes(type)"
        onmouseover="this.title = this.getElementsByClassName('el-input__inner')[0] ?
          this.getElementsByClassName('el-input__inner')[0].value : this.getElementsByClassName('el-textarea__inner')[0].value"
      >
        <el-input
          v-bind="$attrs"
          v-on="bindListeners"
          :value="value"
          :type="type"
          :style="contentStyle"
          :autosize="autoSize || { minRows: 3, maxRows: 3}"
          resize="none"
          :placeholder="$attrs.disabled?'':placeholder || `请输入${label}`"
          maxlength="120"
        ></el-input>
      </div>
      <el-input
        v-else-if="type === 'number'"
        v-bind="$attrs"
        :value="value"
        :style="contentStyle"
        v-on="newListeners"
        type="text"
        :placeholder="$attrs.disabled?'':placeholder || `请输入${label}`"
      ></el-input>
      <el-input
        v-else-if="type === 'temperature'"
        v-bind="$attrs"
        v-on="bindListeners"
        :style="contentStyle"
        :value="value"
        type="number"
        :placeholder="$attrs.disabled?'':placeholder || `请输入${label}`"
      ></el-input>
      <el-radio-group
        v-else-if="type === 'radio'"
        v-bind="$attrs"
        v-on="bindListeners"
        :style="contentStyle"
        :value="value"
        @change="handleChange"
      >
        <el-radio
          v-for="(item,index) in options || optionsData"
          :label="item.value"
          v-bind="item"
          :key="index"
        >{{item.label}}</el-radio>
      </el-radio-group>
      <el-checkbox-group v-else-if="type === 'checkbox'"
                         :style="contentStyle" @change="handleChange">
        <el-checkbox
          v-for="(item,index) in options || optionsData"
          :label="item.value"
          :key="index"
        >{{item.label}}</el-checkbox>
      </el-checkbox-group>
      <form-select
        :style="contentStyle"
        v-else-if="['select','cascader'].includes(type)"
        v-bind="$attrs"
        v-on="bindListeners"
        :type="type"
        :value="value"
        :options="options"
        @change="handleChange"
        :placeholder="$attrs.disabled?'':placeholder || `请选择${label}`"
      ></form-select>
      <div style="display: flex" v-else-if="type === 'selectData'">
        <form-select-data
          v-bind="$attrs"
          :style="contentStyle+';flex: 1'"
          v-on="bindListeners"
          :value="value"
          :options="options"
          @change="handleChange"
          :placeholder="$attrs.disabled?'':placeholder || `请选择${label}`"
        ></form-select-data>
        <template v-if="$attrs.appendHtml">
          <div v-html="$attrs.appendHtml()"></div>
        </template>
      </div>

      <el-date-picker
        :style="contentStyle"
        v-else-if="['date','datetime','year','month','daterange'].includes(type)"
        v-bind="$attrs"
        v-on="bindListeners"
        :value="value"
        :type="type"
        :editable="false"
        :value-format="valueFormat || 'timestamp'"
        @change="handleChange"
        onmouseover="this.title = this.getElementsByClassName('el-input__inner')[0].value"
        :placeholder="$attrs.disabled?'':placeholder || `请选择${label}`"
      ></el-date-picker>

      <form-upload
        :style="contentStyle"
        v-else-if="type === 'file'"
        v-bind="$attrs"
        v-on="bindListeners"
        :value="value"
        @change="handleChange"
      ></form-upload>

      <slot v-else-if="type === 'slot'" :name="prop" :data="value"></slot>

      <form-upload
        :style="contentStyle"
        v-else-if="type === 'prevFile'"
        v-bind="$attrs"
        v-on="bindListeners"
        :value="value"
        @change="handleChange"
      ></form-upload>

<!--        显示图片的缩略图 并且上传 start-->
      <form-upload-picture-thumb
        :style="contentStyle"
        v-else-if="type === 'pictureThumb'"
        v-bind="$attrs"
        v-on="bindListeners"
        :value="value"
        @change="handleChange"
      ></form-upload-picture-thumb>
<!--        显示图片的缩略图 end-->
      <form-slider
        :style="contentStyle"
        v-else-if="type === 'slider'"
        v-bind="$attrs"
        style="padding: 0 10px"
        v-on="bindListeners"
        :value="value"
      ></form-slider>

      <span
        :style="contentStyle"
        v-else-if="type === 'span'"
        v-bind="$attrs"
        v-on="bindListeners"
      >{{$attrs.tips}}</span>

      <span
        :style="contentStyle"
        v-else-if="type === 'value'"
        v-bind="$attrs"
        v-on="bindListeners"
      >{{value}}</span>

      <span
        :style="contentStyle"
        v-else-if="type === 'valueFormatter'"
        v-bind="$attrs"
        v-on="bindListeners"
      >
        {{dealValue()}}
      </span>
      <span v-if="content" class="text-box" style="text-align: left;line-height: 1rem;padding: 10px;font-size: 13px;color: red">{{content}}</span>
      <div v-if="allAppendHtml && allAppendHtmlEvent" @click="allAppendHtmlEvent" v-html="allAppendHtml || allAppendHtml()"></div>
    </div>
</template>

<script>
import { Subject } from "rxjs";
import formSelect from './form-select';
import formSelectData from './form-select-data';
import formUpload from './form-upload';
import formUploadPictureThumb from './form-upload-picture-thumb';
import formSlider from './form-slider';

export default {
  name: "ZbFormListItem",
  components: {
    formSelect,
    formSelectData,
    formUpload,
    formUploadPictureThumb,
    formSlider,
  },
  model:{
    prop: "value",
    event: "input"
  },
  props: {
    $index: [Number,String],
    type: String, // 表单项类型
    autoSize: [Object, Boolean],
    label: String, // label文本
    inline: {
      type: Boolean,
      default: true,
    }, // 是否级联显示
    span: [Number, String], // 所占24列中的多少分
    prop: String, // 绑定表单中的属性，用于表单验证
    height: [String, Number], // 表单项的高度
    alignTop: Boolean, // 内容区是否从顶部开始布局，默认垂直居中
    noPadding: Boolean, // 是否有内边距
    isPrinting: Boolean, // 打印中
    align: {
      type: String,
      default: 'center',
    }, // 打印中
    options: Array,
    formatter:{
      type: Function,
      default: null,
    },
    valueFormat: String, // 时间格式化
    cellLabelWidth: [Number, String], // 单元格label宽度
    hiddenLabel: Boolean, // 是否隐藏label
    showContent: {
      type: Boolean,
      default: true,
    }, // 是否隐藏内容
    show: {
      type: Boolean,
      default: true,
    }, // 是否隐藏所有
    exits: {
      type: Boolean,
      default: true,
    }, // 是否存在所有
    placeholder: String,
    value: {
      type: [Number, String, Array, Date],
    },
    cellInput: Boolean, // 在表格中嵌套使用
    getDict:{
      type: [Function]
    },
    allAppendHtmlEvent:{
      type: [Function]
    },
    allAppendHtml:{
      type: [String,Function],
      default:'',
    },
    content:{
      type: [String,Function],
      default:'',
    },
    // 每个内容的style
    contentStyle:{
      type: [String,Function],
      default:'width:100%;',
    },
  },
  inject: {
    labelWidth: { default: 160 },
    rules: { default: {} },
    formSubject: { default: new Subject() },
  },
  computed: {
    newListeners() {
      return Object.assign(this.$listeners, {
        input:this.limitNumber
      })
    },
    bindListeners() {
      const events = this.$attrs.listeners;
      if (events && Object.keys(events).includes("input")) {
        this.$delete(events, "input");
      }
      return Object.assign(this.$listeners, events);
    },
    formContentStyle() {
      const { labelWidthCup } = this;
      let str = "";
      if (this.hiddenLabel) {
        str = `width: calc(100% ${labelWidthCup} - ${this.changeRem(42)})`;
      } else {
        str = `width: calc(100% - ${labelWidthCup} - ${this.changeRem(10)})`; // Todo  - 18px - 24px
      }
      if (this.noPadding) {
        str = `width: calc(100% - ${labelWidthCup} - ${this.changeRem(
          10
        )}); height: 100%;`;
      }
      return str;
    },
    labelWidthCup() {
      if (this.hiddenLabel) {
        return "-" + this.changeRem(18);
      }
      const val = this.cellLabelWidth || this.labelWidth;
      if (typeof val === "number") {
        return this.changeRem(val);
      }
      if (typeof val === "string") {
        if (val.indexOf("px") > -1) {
          return this.changeRem(val);
        } else if (val.endsWith("%")) {
          return val;
        }
        return this.changeRem(val);
      }
      return this.changeRem(80);
    },
    display() {
      if (this.inline) {
        return "inline-block";
      }
      return "block";
    },
    width() {
      if (this.span) {
        return `calc(100% * (${this.span} / 24))`;
      }
      return "100%";
    },
    heightCup() {
      const val = this.height;
      if (typeof val === "number") {
        return this.changeRem(val);
      }
      if (typeof val === "string") {
        return this.changeRem(val);
      }
      return "";
    },
  },
  data() {
    return {
      validateMsgsProp: {
        msgStatus: true,
        validateMessage: "",
      },
      optionsData: [],
    };
  },
  created() {
    this.formSubject.subscribe((x) => {
      if (x.prop === "all") {
        this.validateMsgsProp.msgStatus = x.msgStatus;
      } else if (x.prop === this.prop) {
        if (x.validateMessage) {
          this.validateMsgsProp.validateMessage = x.validateMessage;
        }
        this.validateMsgsProp.msgStatus = x.msgStatus;
      }
    });
    if (this.type === "radio" && this.$attrs.url) {
      this.getAsyncOptions();
    }
    // 设置默认值
    if (this.$attrs.defaultValue!==undefined){
      this.$emit('input',this.$attrs.defaultValue)
    }
  },
  methods: {
    dealValue(){
      if (this.options && this.options.length){
        for (let i = 0; i < this.options.length; i++) {
          if (this.options[i].value === this.value) return this.options[i].label
        }
      }
      if (this.value && this.formatter){
        return this.formatter(this.value)
      }
      return ''
    },
    handleChange(val) {
      //debugger;
      this.$emit("handleChange", val, this.prop,this.optionsData);
    },
    getAsyncOptions() {
      this.getDict(this.$attrs.url, this.$attrs.params).then((res) => {
        if (res.status === 200) {
          if (this.$attrs.props) {
            const { label, value } = this.props;
            this.optionsData = res.data.map((item) => {
              item.label = item[label];
              item.value = item[value];
              return item;
            });
          }
          this.optionsData = res.data.map((item) => {
            item.label = item.value;
            return item;
          });
        }
      });
    },
    limitNumber(val, num = this.$attrs.dot?this.$attrs.dot:2,max=this.$attrs.max?this.$attrs.max:99999999) {
      val = String(val);
      let value = null;
      if (num === undefined || num == null || num === 0) {
        //正整数
        value = val.replace(/[^0-9]+/g, "");
      } else {
        let re = new RegExp("^\\d+(\\.\\d{0," + num + "})?");
        value = (val.match(re) ? val.match(re)[0] : null) || null;
      }
      if (value>=max){
        value = max
      }
      this.$emit("input", value);
    },
    // 自适应屏幕转换
    changeRem(number) {
      // return parseFloat(number) * Math.min(this.$scale, 1) + "px";
      return parseFloat(number) + "px";
    },
  },
  mounted() {
    //console.log('type:',this.type);
  }
};
</script>


<style lang="scss" scoped>
$border-color: #ebeef3;
$label-bgcolor: #f9fafd;
.page-form-item {
  font-size: 14px;
  font-family: "PingFangSC";
  position: relative;
  vertical-align: top;
  overflow: hidden;
  height: 40px;
  color: #4d4d4d;
  .page-form-item-label {
    height: 100%;
  }
  .left-border {
    position: absolute;
    height: 100%;
    width: 1px;
    left: 0;
    top: 0;
    background-color: $border-color;
    z-index: 999;
  }
  &-label {
    display: inline-block;
    height: calc(100% - 16px);
    background-color: $label-bgcolor;
    border-right: 1px solid $border-color;
    border-left: 1px solid $border-color;
    text-align: center;
    &__text {
      display: inline-block;
      vertical-align: middle;
      line-height: 1.3em;
      width: 80%;
    }
    &::after {
      content: "";
      display: inline-block;
      vertical-align: middle;
      height: 100%;
    }
  }
  .border-right0 {
    border-right: 0;
  }
  &-content {
    display: inline-block;
    vertical-align: top;
    padding: 8px;
    height: calc(100% - 16px);
    &.noLabel {
      border-left: 1px solid $border-color;
    }
    &::after {
      content: "";
      display: inline-block;
      vertical-align: middle;
      height: 100%;
    }
    &.align-top {
      &::after {
        content: "";
        vertical-align: top;
      }
    }
    &.noPadding {
      padding: 0;
    }
  }
  ::v-deep .el-table th {
    background-color: $label-bgcolor;
  }
  ::v-deep .el-radio {
    margin-right: 15px;
  }
  ::v-deep .el-radio__label {
    font-size: 12px;
  }
  ::v-deep .el-input--small .el-input__inner {
    font-size: 12px;
  }
  ::v-deep .el-checkbox {
    font-size: 12px;
  }
  ::v-deep .el-checkbox__label {
    font-size: 12px;
    vertical-align: -2px;
  }
  ::v-deep .el-select {
    width: 100%;
  }
  ::v-deep .el-cascader {
    width: 100%;
  }
  ::v-deep .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 100%;
  }
  ::v-deep .el-form-item.is-success .el-input__inner,
  ::v-deep .el-form-item.is-success .el-input__inner:focus,
  ::v-deep .el-form-item.is-success .el-textarea__inner,
  ::v-deep .el-form-item.is-success .el-textarea__inner:focus {
    border-color: #dcdfe6;
  }
  ::v-deep .el-textarea__inner {
    height: 80px;
  }
  .page-form-item-content {
    height: 100%;
    overflow: hidden;
    ::v-deep .el-form-item {
      margin-bottom: 0;
      .el-input__inner {
        /*height: 100%;*/
      }
      ::v-deep.is-disabled .el-input__inner,
      .el-textarea__inner,
      .el-radio__label {
        color: #4d4d4d;
        /*background: #fff;*/
      }
    }
    .text-box {
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;
      cursor: pointer;
    }
    .slider-box {
      display: flex;
      justify-content: space-between;
      &:first-child {
        flex: 1;
      }
    }
  }
}
.cell-input {
  border: 0;
  height: auto;
  min-height: 66px;
  padding-top: 12px;
  .page-form-item-content {
    padding: 0;
    width: 100%;
    border: 0;
    overflow: initial;
  }
}
</style>
<style lang="scss" scoped>
.page-form-item-tooltip {
  &.el-tooltip__popper.is-light {
    border: 1px solid #f56c6c;
    color: #f56c6c;
  }
  &.el-tooltip__popper.is-light[x-placement^="top"] .popper__arrow {
    border-top-color: #f56c6c;
  }
}
</style>
